<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * paymentAir controller
 * @author Phuc Nguyen - 09/03/2015
 * http://www.facebook.com/phucthuong
 * email : nguyenvanphuc0626@gmail.com
*/
class PaymentAir extends BACKEND_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->language('paymentAir');
		$this->load->language('button');
		if($this->database_connect_status){
			$this->load->model('paymentAir_model');
			$this->set_controller('paymentAir');
			$this->set_model($this->paymentAir_model);
		}
                $this->load->model('user_model');
	}
        
        public function ajaxAutoload(){
             $ajax = $this->paymentAir_model->getInfoAjax($this->session->userdata['user_id']);
             if($ajax[0]->count > 0){
                 $this->view_data['ajax'] = $ajax;
                 $this->load->view('auth/paymentAir/ajaxAutoload', $this->view_data);
             }
        }
        
        private function upload(){
                try
                {
                    $uploaddir  = 'D:/sourceweb/vietbay/www/static/uploads/airlines/';
                    $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
                    if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
                        die("Upload ảnh thất bại!");
                    }
                }
                catch(Exception $err)
                {
                    log_message("error",$err->getMessage());
                    return show_error($err->getMessage());
                }
        }
        
        protected function update($params=NULL){
		if($this->input->server('REQUEST_METHOD')=='POST'){
                        $this->view_data["paymentAir"]                                 = new stdClass();
                        $this->view_data["paymentAir"]->note                           = $this->input->post('note');
                        $this->view_data["paymentAir"]->payment_air                    = $this->input->post('payment_air');
                        $this->view_data["paymentAir"]->owner                          = $this->session->userdata['user_id'];
                        $this->view_data["paymentAir"]->agent_code                     = $this->session->userdata['agent_code'];
                        $this->view_data["paymentAir"]->lastupdated                    = time();
                       
                        $this->load->helper('form');
                        $this->load->helper('character');
                        $this->load->helper('form');
                        $this->load->library('form_validation');
                        $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                        $rules = array(
                           array(
                                'field'   => 'note',
                                'label'   =>  $this->lang->line('note'),
                                'rules'   => 'trim|max_length[255]|xss_clean'
                            )
                        );

                        $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                        $this->form_validation->set_rules($rules);

                        if ($this->form_validation->run()==TRUE){
                            if(isset($params) && $params){
                                //upload image
                                if($_FILES['userfile']['name'] != "" AND $_FILES['userfile']['error'] == 0){
                                    $this->upload();
                                }
                                 //edit data
                                $this->paymentAir_model->update($this->view_data["paymentAir"], $params);
                                $logAction                     = $this->lang->line('update_paymentAir_success').' '.$this->lang->line("payment_air").' '.$this->lang->line("customerID").' '.$params;
                                $customerID                    = $this->input->post('customerID');
                            }

                            /*
                             * insert log payment
                             */

                            unset($this->view_data["paymentAir"]->payment_air);
                            $this->view_data["paymentAir"]->img_url             =   $_FILES['userfile']['name'];
                            $this->view_data["paymentAir"]->booking_id          =   $this->input->post('booking_id');
                            $this->view_data["paymentAir"]->customerID          =   $this->input->post('customerID');
                            $this->view_data["paymentAir"]->note                =   $this->input->post('payment').' '.$this->input->post('note');
                            $this->view_data["paymentAir"]->amount              =   $this->input->post('amount');
                            
                            $this->load->model('paymentlogair_model');
                            $this->paymentlogair_model->create($this->view_data["paymentAir"]);
                            /*
                             * update list booking
                             */
                            $this->load->model('booking_model');
                            $info                   = $this->booking_model->find_by(array('id' => $this->input->post('booking_id')));
                            
                            $ngay_dau_bay           =   json_decode($info[0]->booking);
                            $check                  =   explode("-",$ngay_dau_bay[0]);
                            $info[0]->ngay_dau_bay  =   date("Y-m-d",strtotime(str_replace('/','-',$check[0])));
                            $info[0]->booking_id    =   $this->input->post('booking_id');
                            
                            if($info[0]->payment_method == 2 && $info[0]->booking_types == 1){
                                $agw                    = 0;
                                if(strpos($info[0]->booking,'AGW')){
                                    $json_booking = json_decode($info[0]->booking);
                                    foreach($json_booking as $keys => $values){
                                        if(strpos($values,'AGW')){
                                            $agw = $agw + 1;
                                        }
                                    }
                                }
                                $info[0]->segments      =   (count(json_decode($info[0]->booking)) - $agw) * count(explode("||", $info[0]->booking_customer_name));
                            }

                            $this->load->model('bookhistory_model');
                            unset($info[0]->id);unset($agw);
                            $result = $this->bookhistory_model->create($info[0]);
                            if(!$result){
                                die("Log Booking Fail! Contact Admin!");
                            }
                            
                            $this->booking_model->delete(array('id' => $this->view_data["paymentAir"]->booking_id));
                            unset($this->view_data["paymentAir"]);
                            
                            //update money contacts
                            $this->load->model('listcustomers_model');
                            $this->listcustomers_model->updateMoneyTotal($customerID,$this->input->post('sale_fare_fake'),date('Y-m-d H:i:s',$this->input->post('createdTime')));
                            
                            //updated list CSKH
                            $info_CSKH                          = $this->listcustomers_model->find_by(array('customerID'=>$info[0]->customerID));
                            $l_CSKH                             = new stdClass();
                            $l_CSKH->customerID                 = $info[0]->customerID;
                            $l_CSKH->name                       = $info_CSKH[0]->name;
                            $l_CSKH->phone                      = $info_CSKH[0]->phone;
                            $l_CSKH->booking_place_code         = $info[0]->booking_place_code;
                            $l_CSKH->airline                    = $info[0]->airline;
                            $l_CSKH->ngay_dau_bay               = $info[0]->ngay_dau_bay;
                            $l_CSKH->phone_callstatus           = $this->input->post('phone_callstatus');
                            $l_CSKH->owner                      = $this->session->userdata['user_id'];
                            $l_CSKH->agent_code                 = $this->session->userdata['agent_code'];
                            $l_CSKH->lastupdated                = date("Y-m-d H:i:s",time());
                            
                            $this->load->model('flyTomorrow_model');
                            $resultFly      = $this->flyTomorrow_model->create($l_CSKH);
                            if(!$resultFly){
                                die("Update list CSKH fail!COntact Admin!");
                            }
                            unset($resultFly);
                            unset($l_CSKH);
                            /*
                             * updated list CSKH rate booker
                             */
                            $r_CSKH                             = new stdClass();
                            $r_CSKH->customerID                 = $info[0]->customerID;
                            $r_CSKH->name                       = $info_CSKH[0]->name;
                            $r_CSKH->phone                      = $info_CSKH[0]->phone;
                            $r_CSKH->ngay_dau_bay               = $info[0]->ngay_dau_bay;
                            $r_CSKH->booker                     = $info[0]->owner;
                            $r_CSKH->real_fare                  = $info[0]->real_fare;
                            $r_CSKH->lastupdated                = date("Y-m-d H:i:s",time());
                            $this->load->model('customerAssess_model');
                            $_resultFly      = $this->customerAssess_model->create($r_CSKH);
                            if(!$_resultFly){
                                die("Update list CSKH rate booker fail!Contact Admin! update > 162");
                            }
                            
                            unset($_resultFly);
                            unset($r_CSKH);
                            
                            /*
                             * update money users and ticket
                             */
                            $this->load->model('ticketWorkers_model');
                            $_u_cash_booking    = $this->user_model->updateCashBooking(array('user_id'=>$info[0]->owner));
                            if($info[0]->payment_method == 2 && $info[0]->ticket_workers){
                               $_t_cash_booking    = $this->ticketWorkers_model->updateCashBooking(array('id'=>$info[0]->ticket_workers)); 
                            }
                            if(!$_u_cash_booking){
                                die("Update list money users-ticket fail!Contact Admin! update > 174");
                            }
                            unset($_u_cash_booking);unset($_t_cash_booking);
                             /*
                             * updated list KToan
                             */
//                            $r_KT                               = new stdClass();
//                            $r_KT->customerID                   = $info[0]->customerID;
//                            $r_KT->name                         = $info_CSKH[0]->name;
//                            $r_KT->booking                      = $info[0]->booking;
//                            $r_KT->booking_place_code           = $info[0]->booking_place_code;
//                            $r_KT->airline                      = $info[0]->airline;
//                            $r_KT->booker                       = $info[0]->owner;
//                            $r_KT->ticket_workers               = $info[0]->ticket_workers;
//                            $r_KT->real_fare                    = $info[0]->real_fare;
//                            $r_KT->agent_code                   = $info[0]->agent_code;
//                            $r_KT->lastupdated                  = date("Y-m-d H:i:s",$info[0]->lastupdated);
//                            $r_KT->createdTime                  = date("Y-m-d H:i:s",$info[0]->createdTime);
//                            
//                            $this->load->model('accountancy_model');
//                            $_result_KT      = $this->accountancy_model->create($r_KT);
//                            unset($r_KT);
                            unset($info_CSKH);
                            //book statictis
                            $this->load->model('bookStatistic_model');
                            $statistic = array(
                                'owner'         => $this->session->userdata['user_id'],
                                'lastupdated'   => date("Y-m-d")
                            );

                            $query = $this->bookStatistic_model->updateStatisticBookOk($statistic);
                            if(!$query){
                                $this->view_data["statistic"]                   = new stdClass();
                                $this->view_data["statistic"]->booking_ok       = 1;
                                $this->view_data["statistic"]->owner            = $statistic['owner'];
                                $this->view_data["statistic"]->agent_code       = $this->session->userdata['agent_code'];
                                $this->view_data["statistic"]->lastupdated      = $statistic['lastupdated'];

                                $this->bookStatistic_model->create($this->view_data["statistic"]);
                            }
                    
                            if($customerID){
                                    $this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
                                    $paramAdminLog  = array(
                                        'userid'            => $this->session->userdata['user_id'],
                                        'lastLogin'         => date('Y-m-d :H:i:s',time()),
                                        'ip'                => $_SERVER['REMOTE_ADDR'],
                                        'logAction'         => $logAction,
                                        'agent_code'        => $this->session->userdata['agent_code']
                                    );
                                    $this->user_model->insertUserAdminLog($paramAdminLog);

                                    redirect('auth/paymentAir/');
                            }
                        }

            }
            
            $this->load->model('paymentAir_model');
            $this->load->model('language_model');

            if(isset($params)){
                    $paymentAir_query	= $this->paymentAir_model->find_by(array('id' => $params));
                    
                    if(!isset($paymentAir_query[0])){
                            $this->session->set_flashdata('flash_message', $this->lang->line('not_exists'));
                            redirect(site_url('auth/paymentAir'));
                            exit();
                    }

                    $this->view_data['paymentAir']				= $paymentAir_query[0];
            }

           $this->view_data['js'] = array(
				base_url().'static/templates/backend/js/main.js',
				base_url().'third_party/ckfinder/ckfinder.js',
				base_url().'static/templates/backend/js/ckfinder_function.js'
		);
            $this->view_data['css'] = array(
            );
            $this->load->view('auth/paymentAir/edit', $this->view_data);
	}

}